/**
 * 系统管理  设备绑定
 */
<template>
  <div style="width: 100%;height: 100%">
    <!-- 搜索筛选 -->
    <el-row :model="formInline" style="height: 5%;width: 100%;display: flex;align-items: center;">
      <el-col :span="0.5" style="margin-right: 0.5vw">
        <el-text size="large">搜索:</el-text>
      </el-col>
      <el-col :span="4" style="display: flex;align-items: center;justify-content: center;">
        <el-input size="large" v-model="formInline.serialCode" placeholder="请输入设备序列号"></el-input>
      </el-col>
      <el-col :span="4" style="display: flex;">
        <el-button size="large" style="background-color:#04c1a5;color:#fff" @click="searchDevice">
          <font-awesome-icon icon="fas fa-search" />
          <span style="margin-left:1vh">查询</span>
        </el-button>
        <el-button size="large" style="background-color:#04c1a5;color:#fff" @click="bindFormVisible=true">
          <font-awesome-icon icon="fas fa-plus" />
          <span style="margin-left:1vh">手动绑定</span>
        </el-button>
      </el-col>
      <el-col :span="16">
      </el-col>
    </el-row>

    <el-row style="
    background-color: white;
    height: 35%;
    margin-top: 2vh;
    margin-bottom: 10px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
      <filter-list :filter-rows="rows" @updateList="updateList"/>
    </el-row>

    <!-- 分页组件5%-->
    <el-row style="display: flex;justify-content: flex-end;align-items: center;height: 5%;width: 100%;margin-bottom: 10px">
      <el-pagination
          v-model:current-page="pageParam.pageNo"
          v-model:page-size="pageParam.pageSize"
          v-model:total="pageParam.totalCount"
          :page-sizes="[1, 10, 15, 20]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes,prev, pager, next, jumper"
          :total="100"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-row>
    <!--列表-->
    <el-table
    :header-cell-style=" { background: '#F7FBFE' , color: '#000' , 'text-align': 'center' }" 
    size="large"
    :cell-style="{'text-align':'center'}"
    style="width: 100%;height: 50%"
    :data="deviceData"
    v-loading="loading"
    highlight-current-row 
    class="customer-table" 
    border 
    element-loading-text="拼命加载中">
<!--      <el-table-column  sortable prop="id" label="设备编号" width="150">-->
<!--      </el-table-column>-->
      <el-table-column  sortable prop="serialCode" label="序列号" width="240">
        <template #default="scope">
          <div>{{removeSubstring(scope.row.serialCode,"ynu",false,true)}}</div>
        </template>
      </el-table-column>
      <el-table-column  sortable prop="status" label="设备状态" width="170">
      </el-table-column>

      <el-table-column  sortable prop="model" label="型号" width="200">
      </el-table-column>
      <el-table-column  sortable prop="size" label="设备尺寸" min-width="150">
      </el-table-column>
      <el-table-column sortable prop="productionTime" label="生产时间" min-width="180">
        <template v-slot="scope">
          {{ formatProductionTime(scope.row.productionTime) }}
        </template>
      </el-table-column>

      <el-table-column align="center"  fixed="right" label="操作" min-width="200">
        <template v-slot="scope">
          <el-button  size="default" style="background-color:#edf7f6;color:#4CAF50;" @click="showBindForm(scope.row.deviceId)">
            <font-awesome-icon icon="faS fa-link" />
            <span style="margin-left:1vh">绑定用户</span>
            </el-button>
        </template>
      </el-table-column> 
    </el-table>
    <el-dialog title="手动绑定" v-model="bindFormVisible" width="30%" align-center center :before-close="handleClose">
      <el-form style="display: flex;align-items: center;justify-content: center;width: 100%;height: 100%;flex-wrap: wrap">
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">患者手机号:</el-text>
          <el-input style="width: 80%" v-model="bindForm.username" placeholder="请输入要绑定的患者手机号" autocomplete="off"/>
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">设备编号:</el-text>
          <el-input style="width: 80%" v-model="bindForm.deviceId" placeholder="请输入要绑定的设备编号" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" style="background-color: #04c1a5;border: 0" @click="manualBinding">保存</el-button>
      </span>
      </template>
    </el-dialog>
    <!-- 分页组件 -->
<!--    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>-->
  </div>
</template>

<script setup>
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import {onMounted, ref} from 'vue';
import doctor from "@/api/doctor.js";
import {ElMessage} from "element-plus";
import * as dateUtils from "@/utils/dateUtils.js";
import FilterList from "@/components/tableViews/filterList.vue";
import {removeSubstring} from "@/utils/strFormat.js";
const bindFormVisible = ref(false)
const loading = ref(false);
const editFormVisible = ref(false);
const title = ref('添加');
const bindForm = ref({
  deviceId:'',
  username:''
})
const formInline = ref({
  serialCode:''
});
const deviceData = ref([]);
const pageParam = ref({
  pageNo:1,
  pageSize:10,
  totalCount:10,
  totalPages:10,
  nextPage:0,
  prePage:0,
  hasPre:false,
  hasNext:true,
});


//按钮查询过滤
const rows = ref([
  { label: '状态', buttons: [
      { text: '未绑定', value: null, selected: true },
      // { text: '申请绑定', value: 0, selected: false },
      // { text: '已绑定', value: 1, selected: false },
      // { text: '拒绝绑定', value: 2, selected: false },
    ] },
  { label: '使用期限', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '一个月',value: '一个月', selected: false },
      { text: '两个月', value: '两个月',selected: false },
      { text: '三个月', value: '三个月',selected: false },
      { text: '半年', value: '半年',selected: false },
      { text: '一年', value: '一年',selected: false },
      { text: '一年以上', value: '一年以上',selected: false },
    ] },
  { label: '型号', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '睡眠呼吸监测仪',value: '睡眠呼吸监测仪', selected: false },
      { text: '慢阻肺检测仪', value: '慢阻肺检测仪',selected: false },
    ] },
  { label: '生产时间', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: null,selected: false },
    ] },
  // { label: '激活时间', buttons: [
  //     { text: '-全部-', value: null,selected: true },
  //     { text: '刚刚',value: 1, selected: false },
  //     { text: '最近1天', value: 2,selected: false },
  //     { text: '最近7天', value: 7,selected: false },
  //     { text: '最近两周', value: 14,selected: false },
  //     { text: '最近1个月', value: 30,selected: false },
  //     { text: '最近3个月', value: 90,selected: false },
  //     { text: '最近一年', value: 365,selected: false },
  //     { text: '一年以上', value: null,selected: false },
  //   ] },
  // { label: '过期时间', buttons: [
  //     { text: '-全部-', value: null,selected: true },
  //     { text: '刚刚',value: 1, selected: false },
  //     { text: '最近1天', value: 2,selected: false },
  //     { text: '最近7天', value: 7,selected: false },
  //     { text: '最近两周', value: 14,selected: false },
  //     { text: '最近1个月', value: 30,selected: false },
  //     { text: '最近3个月', value: 90,selected: false },
  //     { text: '最近一年', value: 365,selected: false },
  //     { text: '一年以上', value: null,selected: false },
  //   ] },
]);
const updateList = (newRows) =>{
  const deviceListQuery = {
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  };
  // 调用更新方法
  updateDeviceListQuery(newRows, deviceListQuery);
  requestDeviceList(deviceListQuery)
}

//分页模块
const updatePageParams = (pageData)=> {
  pageParam.value.pageNo = pageData.pageNo;
  pageParam.value.pageSize = pageData.pageSize;
  pageParam.value.totalCount = pageData.totalCount;
  pageParam.value.totalPages = pageData.totalPages;
  pageParam.value.nextPage = pageData.nextPage;
  pageParam.value.hasNext = pageData.hasNext;
  pageParam.value.prePage = pageData.prePage;
  pageParam.value.hasPre = pageData.hasPre;
}
const handleCurrentChange = (newPage)=>{
  pageParam.value.pageNo = newPage;
  const bindingDeviceQuery = {
    status:'',
    currentTime:'',
    applicationTimeEnd:'',
    processingTimeEnd:'',
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  };
  console.log(newPage)
  // 调用更新方法
  updateDeviceListQuery(rows.value, bindingDeviceQuery);
  //执行查询
  requestDeviceList(bindingDeviceQuery)
}
const handleSizeChange = ()=>{
  const deviceListQuery = {
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  updateDeviceListQuery(rows.value,deviceListQuery)
  requestDeviceList(deviceListQuery)
}


//列表查询
onMounted(() => {
  // 获取设备
  getDevicesList();
});
const getStatusText = (statusCode) => {
  switch (statusCode) {
    case 0:
      return "申请绑定";
    case 1:
      return "已绑定";
    case 2:
      return "拒绝绑定";
    default:
      return "未绑定";
  }
};
const getDevicesList = ()=>{
  const deviceListQuery = {
    status: null,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  };
  requestDeviceList(deviceListQuery)
}
const requestDeviceList = (deviceListQuery)=>{
  loading.value = true;
  doctor.deviceListSearch(deviceListQuery)
      .then((res) => {
        console.log("binding",res)
        if (res.data.code === 200) {
          // 将状态码转换为中文描述
          deviceData.value = res.data.data.result.map(device => ({
            ...device,
            status: getStatusText(device.status)
          }));
        }
        updatePageParams(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(()=>{
        loading.value = false;
      });
}
function updateSelectedValue(buttons) {
  for (const button of buttons) {
    if (button.selected) {
      return button.value;
    }
  }
  return null;
}
function updateTime(buttons, currentDate) {
  for (const button of buttons) {
    if (button.selected) {
      if (button.value === null) {
        return null;
      } else {
        const time = new Date();
        time.setDate(time.getDate() - button.value);
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    }
  }
  return currentDate; // 默认取当前时间
}
function updateDeviceListQuery(rows, deviceListQuery) {
  deviceListQuery.status = updateSelectedValue(rows[0].buttons);
  deviceListQuery.expirationDate = updateSelectedValue(rows[1].buttons);
  deviceListQuery.model = updateSelectedValue(rows[2].buttons);
  deviceListQuery.currentTime = dateUtils.getCurrentDate();
  deviceListQuery.productionTimeEnd = updateTime(rows[3].buttons,deviceListQuery.currentTime);
}
//格式化生产时间
const formatProductionTime = (isoString) => {
  const date = new Date(isoString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

//编辑弹窗
const manualBinding = ()=>{
  const bindingDeviceEditQuery = {
    username:bindForm.value.username,
    deviceId:bindForm.value.deviceId
  }
  doctor.bindingDevice(bindingDeviceEditQuery)
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage.success("绑定成功")
        }
        getDevicesList()
        bindFormVisible.value = false
      })
      .catch((err) => {
        bindFormVisible.value = false
        console.log(err);
      });
}
const showBindForm = (deviceId)=>{
  bindFormVisible.value = true;
  bindForm.value.deviceId = deviceId;
}
const handleClose = ()=>{
  bindForm.value.deviceId = '';
  bindForm.value.username = '';
  bindFormVisible.value = false;
}

//信息查询
const searchDevice = ()=>{
  const deviceListQuery = {
    serialCode: formInline.value.serialCode,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  updateDeviceListQuery(rows.value,deviceListQuery)
  requestDeviceList(deviceListQuery)
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
/* :deep(.customer-no-border-table th){
    border:none;
}
:deep(.customer-no-border-table td,.customer-no-border-table th.is-leaf)  {
  border:none;
} */
::v-deep .customer-table th{
    border:none;
  }
  ::v-deep .customer-table td,.customer-table th.is-leaf {
  border:none;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
	/* background-color:#04c1a5; */
  background-color: green;   
    color: #fff;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled) {
	background-color: #04c1a5;
}
/* ::v-deep {
  .el-pagination.is-background .el-pager li:not(.disabled) {
    background-color: #fff;   // 进行修改未选中背景和字体
    // color: #fff;
  }
  .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: green;   // 进行修改选中项背景和字体
    color: #fff;
  }
} */

</style>